package com.note.backend.service.impl.user.account;


import com.note.backend.pojo.User;
import com.note.backend.service.impl.utils.UserDetailsImpl;
import com.note.backend.service.user.account.LoginService;
import com.note.backend.utils.JwtUtil;
import com.note.backend.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@Service
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;

    public Result getToken(String username, String password) {
        try {
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(username, password);
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
            User user = loginUser.getUser();
            String jwtToken = JwtUtil.createJWT(user.getId().toString());
            Map<String, String> map = new HashMap<>();
            map.put("id", user.getId().toString());
            map.put("username", user.getUsername());
            map.put("jwtToken", jwtToken);
            log.info("{}登录成功", username);
            return Result.success(map);
        } catch (Exception e) {
            log.info("{}", e.getMessage());
            return Result.error("用户名或密码错误");
        }
    }
}
